<template>
    <div>
        <van-tabs v-model="activeTab" color="lightblue">
            <van-tab title="用户登录">
                <br>
                <van-field
                        v-model="loginUser.identify"
                        name="identify"
                        label="用户名"
                        placeholder="用户名|电子邮箱|手机号码"
                />
                <van-field
                        v-model="loginUser.password"
                        type="password"
                        name="password"
                        label="密码"
                        placeholder="密码"
                />

                <van-row>
                    <van-col offset="2" span="20" style="text-align: center">
                        <van-image style="vertical-align: middle"
                                   :src="'/commons/validateCode/servletRandomCodeImage?token='+token+'&tm='+timer"/>
                        &nbsp;<van-button plain hairline type="default" @click="changeRandomCodeImg"> 换一张</van-button>
                    </van-col>
                </van-row>

                <van-field
                        v-model="loginUser.validateCode"
                        type="text"
                        name="validateCode"
                        label="验证码"
                        placeholder="验证码"
                />
                <div style="margin: 16px;">
                    <van-button round block type="info" @click="doLogin">登录</van-button>
                </div>

            </van-tab>
            <van-tab title="用户注册">
                <br>
                <van-field
                        v-model="regUser.identify"
                        name="identify"
                        label="用户名"
                        placeholder="电子邮箱|手机号码"
                />
                <van-row>
                    <van-col offset="4" span="16" style="text-align: center;padding: 10px">
                        <van-button color="#007d65" plain hairline block type="default" @click="sendValidateCode">
                            发送验证码
                        </van-button>
                    </van-col>
                </van-row>

                <van-field
                        v-model="regUser.password"
                        type="password"
                        name="password"
                        label="密码"
                        placeholder="密码"
                />
                <van-field
                        v-model="regUser.confirmPass"
                        type="password"
                        name="confirmpass"
                        label="确认密码"
                        placeholder="确认密码"
                />
                <van-field
                        v-model="regUser.validateCode"
                        type="text"
                        name="validateCode"
                        label="验证码"
                        placeholder="验证码"
                />
                <div style="margin: 16px;">
                    <van-button round block type="primary" @click="doReg">注册</van-button>
                </div>

            </van-tab>
        </van-tabs>
    </div>
</template>

<script>
    //使用jsonwebtoken生成客户端的token
    import request from "@/util/request";
    import graceChecker from "@/util/graceChecker";
    import myCookie from "@/util/myCookie";

    let jwt = require("jsonwebtoken");

    export default {
        name: "MymLogin",
        data() {
            return {
                activeTab: '用户登录',
                loginUser: {
                    identify: '',
                    password: '',
                    validateCode: ''
                },
                token: jwt.sign({data: new Date().getMilliseconds()}, 'www.simoniu.com', {expiresIn: 6000 * 30}), //表示客户端的一个唯一的标识符
                timer: new Date().getTime(),
                regUser: {
                    identify: '',
                    password: '',
                    confirmPass: '',
                    validateCode: ''
                },
            }
        },
        mounted() {

        },
        methods: {
            //更新图片验证码
            changeRandomCodeImg() {
                this.timer = new Date().getTime();
            },

            async doLogin() {
                if (await this.checkValidateCode(this.loginUser.validateCode)) {
                    //执行真正的用户登录
                    this.$store.dispatch("Login", this.loginUser).then(resp => {
                        if (resp.data.code === 200) {
                            this.$toast.success('登录成功！');
                            console.log("-----以下是登录成功的用户信息-----");
                            console.log(resp.data.data);
                            localStorage.setItem("loginSuccessUserInfo.simoniu.com", JSON.stringify(resp.data.data));
                            setTimeout("javascript:window.location.href='/mIndex'", 2000);
                        } else {
                            this.$toast.fail('用户名或者密码错误！');
                        }
                    }).catch(err => {
                        console.log(err);
                    })
                }
            },

            //给手机或者邮箱发送验证码
            async sendValidateCode() {
                let regUser ={
                    identify: this.regUser.identify,
                    token: this.token
                }
                this.$store.dispatch("SendMessageToMobileOrEmail",regUser).then(resp=>{
                    if (resp.data.code === 200) {
                        this.$toast.success('验证码发送成功！');
                    }
                }).catch(err=>{
                    console.log(err);
                })
            },

            //检查验证码
            async checkValidateCode(validateCode) {
                let flag;
                await request.get('/commons/msg/auth', {
                    params: {
                        token: this.token,
                        //code: this.regUser.validateCode
                        code: validateCode
                    }
                }).then(resp => {
                    if (resp.data.code === 400) {
                        //Message.error('验证码验证失败！');
                        this.$toast.fail('验证码验证失败！')
                        flag = false;
                    } else {
                        flag = true;
                    }
                }).catch(err => {
                    console.log(err);
                });
                return flag;
            },

            //检查电子邮箱或者手机号码是否已经被注册
            async checkIdentifyIsReg() {
                let flag;
                await request.get('/commons/users/exist/identify', {
                    params: {
                        identify: this.regUser.identify
                    }
                }).then(resp => {
                    if (resp.data.code === 200) {
                        console.log("该账号是否已经被注册：" + resp.data.data);
                        //resp(resp.data.data);
                        flag = resp.data.data;
                    }
                }).catch(err => {
                    console.log(err);
                });
                return flag;
            },

            //执行用户注册...
            async doReg() {
                console.log('执行用户注册');
                let result = await this.checkIdentifyIsReg();
                console.log("result=" + result);
                if (result) {
                    this.$toast.fail('该手机或者邮箱已经被注册！');
                    return;
                }
                //console.log('继续注册....')
                //验证的验证码
                if (await this.checkValidateCode(this.regUser.validateCode)) {
                    //验证码也验证成功。
                    //判断一下identify究竟是电子邮箱还是手机号码
                    if (graceChecker.check(this.regUser.identify, "email")) {
                        this.regUser.email = this.regUser.identify;
                        this.regUser.mobile = "";
                    } else if (graceChecker.check(this.regUser.identify, "phoneno")) {
                        this.regUser.mobile = this.regUser.identify;
                        this.regUser.email = "";
                    } else {
                        this.$toast.fail('注册信息格式非法！')
                        //Message.error('注册信息格式非法！')
                        return;
                    }

                    //以下是表单验证
                    if (this.regUser.password.length < 6) {
                        //Message.error('密码不能小于6位！');
                        this.$toast.fail('密码不能小于6位！');
                        return;
                    }
                    if (this.regUser.password != this.regUser.confirmPass) {
                        //Message.error('确认密码与密码不一致！');
                        this.$toast.fail('确认密码与密码不一致！');
                        return;
                    }
                    //执行用户注册
                    /*
                    request.post('/commons/users/', this.regUser).then(resp => {
                        if (resp.data.code === 200) {
                            //Message.success('注册成功！');
                            this.$toast.success('注册成功！')
                            //注册成功之后自动切换到登录的tab;
                            //setTimeout(this.changeTab('userlogin'), 2000);
                        }
                    }).catch(err => {
                        console.log(err);
                    });*/
                    this.$store.dispatch("Reg",this.regUser).then(resp=>{
                        if (resp.data.code === 200) {
                            this.$toast.success('注册成功！')
                            //注册成功之后自动切换到登录的tab;
                            this.regUser.identify='';
                            this.regUser.password='';
                            this.regUser.confirmPass='';
                            this.regUser.validateCode='';
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                }
            }
        }
    }
</script>

<style scoped>

</style>